// pages/paperinfo/paperinfo.js
import { pDBPost } from '../../db/pDBPost.js';
var util = require('../../utils/util.js');  

Page({

  /**
   * 页面的初始数据
   */
  data: 
  {
    paperid:null,
    papertitle: null,
    paperinferno: null,
    papertype: null,
    paperadding: null,
    paperimage:null,
    paperowner: null,
    paperownerid: null,
    paperrentrecord: null,
    paperrentdate: null,

    hosterid: null,
    hostername: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    //收藏功能，实例化pDBPost,传入参数postid
    this.dbPost = new pDBPost(options.paperid)
    console.log('pDBPost实例化成功，调用函数...')
    this.postData = this.dbPost.getPostItemById().data
    this.setData({ 
      post: this.postData
    })


    var that = this

    
    
    this.setData(
      {
        paperid: options.paperid,
        hosterid: options.hosterid
      }
    )
    /* 初始化数据库 */
    const db = wx.cloud.database()
    const _ = db.command

    db.collection('Hoster').where
      ({
        _openid: _.eq(this.data.hosterid)
      })
      .get
      ({
        success: res => {
          this.setData(
            {
              hostername: res.data[0].names,
            }
          )
          console.log('用户名查询成功:', res.data)

        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '查询记录失败'
          })
          console.error('数据库查询失败', err)
        }
      })

    db.collection('Paper').where
      ({
        _id: _.eq(this.data.paperid)
      })
      .get
      ({
        success: res => {
          this.setData(
            {
              papertitle: res.data[0].title,
              paperpubdate: util.formatTime(res.data[0].pubdate),
              papertype: res.data[0].ptype,
              paperadding: res.data[0].adding,
              paperimage: res.data[0].image,
              paperowner: res.data[0].owner,
              paperownerid: res.data[0].ownerid,
              paperrentrecord: res.data[0].rentrecord,
              paperrentdate: res.data[0].rentdate,
            }
          )
          console.log('数据库查询成功:', res.data)

        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '查询记录失败'
          })
          console.error('数据库查询失败', err)
        }
      })


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },


  //点击收藏按钮对应的方法
  onCollectionTap: function (event) {
    var newData = this.dbPost.collect()   //调用DBPost的collect方法
    // console.log(newData)
    //重新绑定数据
    this.setData({
      'post.collectionStatus': newData.collectionStatus,
      'post.collectionNum': newData.collectionNum
    })

    wx.showToast({
      title: newData.collectionStatus ? "收藏成功" : "取消收藏",
      duration: 1000,
      icon: "success",
      mask: true
    })
  },

  //借阅按钮
  rentpaper: function () {

    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    console.log("当前时间戳为：" + timestamp);

    this.setData
      ({
        takenhour: timestamp
      })


    if (this.data.hostername != '无') {
      var aflag = 0
      var paperownertem = this.data.paperowner
      var paperowneridtem = this.data.paperownerid
      var length = paperownertem.length
      var paperrentrecordtem = this.data.paperrentrecord
      var paperrentdatetem = this.data.paperrentdate

      for (var i = 0; i < length; i++) {
        if (paperowneridtem[i] == this.data.hosterid) {
          wx.showToast({
            title: '您已经借阅此书',
            icon: 'error',
            duration: 2000          //提示的延迟时间
          })
          aflag = 1
          break
        }
      }

      for (var j = 0; j < length; j++) {
        if (paperowneridtem[j] == '空' && aflag == 0) {
          paperrentrecordtem = paperrentrecordtem + 1
          paperowneridtem[j] = this.data.hosterid
          paperownertem[j] = this.data.hostername
          paperrentdatetem[j] = this.data.takenhour
          this.setData
            ({
              paperrentdate: paperrentdatetem,
              paperowner: paperownertem,
              paperownerid: paperowneridtem,
              paperrentrecord: paperrentrecordtem
            })
          wx.cloud.callFunction
            ({
              // 云函数名称
              name: 'rentpaper',
              // 传给云函数的参数
              data:
              {
                paperid: this.data.paperid,
                paperowner: this.data.paperowner,
                paperownerid: this.data.paperownerid,
                hostername: this.data.hostername,
                hosterid: this.data.hosterid,
                paperrentrecord: this.data.paperrentrecord,
                paperrentdate: this.data.paperrentdate,
              },

              success: function (res) {
                console.log('rentpaper success')
                console.log(res)
              },

              fail: console.error
            })

          wx.showToast({
            title: '借书成功',
            icon: 'error',
            duration: 2000          //提示的延迟时间
          })
          break

        }
      }



    } else {
      wx.showToast({
        title: '你必须先实名注册',
        icon: 'error',
        duration: 2000          //提示的延迟时间
      })
    }

  },


  ///还书按钮
  returnpaper: function () {
    var paperownertem = this.data.paperowner
    if (this.data.hostername != '无') {
      var paperownertem = this.data.paperowner
      var paperowneridtem = this.data.paperownerid
      var length = paperownertem.length

      for (var i = 0; i < length; i++) {
        if (paperowneridtem[i] == this.data.hosterid) {
          paperowneridtem[i] = '空'
          paperownertem[i] = '无人'
          this.setData
            ({
              paperowner: paperownertem,
              paperownerid: paperowneridtem
            })
        }
        wx.cloud.callFunction({
          // 云函数名称
          name: 'returnpaper',
          // 传给云函数的参数
          data: {
            paperid: this.data.paperid,
            paperownerid: this.data.paperownerid,
            paperowner: this.data.paperowner
          },
          success: function (res) {
            console.log(res)
          },
          fail: console.error
        })


        wx.showToast({
          title: '还书成功！',
          icon: 'error',
          duration: 2000          //提示的延迟时间
        })

      }

    } else {
      wx.showToast({
        title: '你必须先实名注册',
        icon: 'error',
        duration: 2000          //提示的延迟时间
      })
    }
  }
})